package com.sgb.kjwl.view.ui.activity.self.packers;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.activity.ComponentActivity;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtSelfTeamEmploymentEditBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.packers.OtherAskTransmitEntity;
import com.sgb.kjwl.model.entity.self.SelfEmploymentEditEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.PointUtils;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.packers.NewTextAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.view.ui.fragment.packers.OtherAskFragment;
import com.sgb.kjwl.view.widget.packers.PackerSignUpWindow;
import com.sgb.kjwl.view.widget.SalaryRegionPopWindow;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.self.packers.SelfTeamEmploymentEditModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;


/**
 * description:灵活用工发布及编辑
 *
 * @author liWei
 * @date 2020/11/10
 * first:写在前面，我们在使用点击事件的时候，当使用到view的id的时候尽量使用if的方式，请不要使用到switch case，if对于
 * 性能的消耗较小
 */
public class SelfTeamEmploymentEditActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private AtSelfTeamEmploymentEditBinding binding;

    @Inject
    SelfTeamEmploymentEditModel viewModel;

    private SelfEmploymentEditEntity entity;

    private List<PickSelectEntity> pickEmploymentSalaryUnit;
    private List<AddressEntity> pickWorkType;
    private List<PickSelectEntity> pickWorkerType;
    private List<PickSelectEntity> pickWorkerStatus;
    private List<PickSelectEntity> pickEmploymentUnit;
    private int mCompanyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);

    /**
     * 一级联动数据
     */
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 二级联动数据
     */
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    /**
     * 三级联动数据
     */
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    private ImageAdapter mPicAdapter;
    private NewTextAdapter mNewTextAdapter;

    private List<String> mUploadImgList;
    /**
     * 防止重复上传
     */
    private Map<String, String> mCacheImgMap;
    private List<File> fileList;
    private int mCurPicNum;

    private String categoryNo = "";
    private String industryNo = "";
    /**
     * 薪资标准弹窗
     */
    private SalaryRegionPopWindow salaryPopWindow;
    private PackerSignUpWindow typeSelectWindow;

    private List<String> workTypeListNO;
    private int selectPosition;
    private boolean isChange;
    private boolean isFirst;
    private OtherAskTransmitEntity addField;
    private int workCityPosition3;
    private String workName;
    private String workNo;

    public static void start(Context context, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, SelfTeamEmploymentEditActivity.class);
        ((SelfTeamEmploymentActivity) context).startActivityForResult(intent, requestCode);
    }

    public static void start(ComponentActivity context, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, SelfTeamEmploymentEditActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    public static void start(Context context, String no, int requestCode) {
        Intent intent = new Intent();
        intent.putExtra("no", no);
        intent.setClass(context, SelfTeamEmploymentEditActivity.class);
        ((SelfTeamEmploymentActivity) context).startActivityForResult(intent, requestCode);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (TextUtils.isEmpty(getIntent().getStringExtra("no"))) {
            mActionBar.setTitle("用工发布");
        } else {
            mActionBar.setTitle("编辑用工");
            viewModel.detailEmployment(getIntent().getStringExtra("no"));
        }

        String salaryType = getIntent().getStringExtra("salaryType");
        String salaryTypeName = getIntent().getStringExtra("salaryTypeName");
        int salaryPosition = getIntent().getIntExtra("salaryPosition", 0);
        String industryNo = getIntent().getStringExtra("industryNo");
        String industryName = getIntent().getStringExtra("industryName");
        int workCityPosition1 = getIntent().getIntExtra("workCityPosition1", 0);
        String categoryNo = getIntent().getStringExtra("categoryNo");
        String categoryName = getIntent().getStringExtra("categoryName");
        int workCityPosition2 = getIntent().getIntExtra("workCityPosition2", 0);
        workNo = getIntent().getStringExtra("workNo");
        workName = getIntent().getStringExtra("workName");
        workCityPosition3 = getIntent().getIntExtra("workCityPosition3", 0);
        String workerPerson = getIntent().getStringExtra("用工人数");

        if (!TextUtils.isEmpty(industryNo) && !TextUtils.isEmpty(categoryNo)) {
            entity.setIndustryNo(industryNo);
            entity.setIndustryName(industryName);
            entity.setCategoryNo(categoryNo);
            entity.setCategoryName(categoryName);
            isChange = true;
            this.categoryNo = categoryNo;
            binding.etCategoryName.setContent(String.format("%s%s%s",industryName,"".equals(categoryName) ? "" : "-",categoryName),17);
            viewModel.opt1 = workCityPosition1;
            viewModel.opt2 = workCityPosition2;
        }

        if (!TextUtils.isEmpty(salaryType)) {
            binding.etSalaryUnit.setContent(salaryTypeName);
            entity.setSalaryType(Integer.valueOf(salaryType));
            binding.etSalary.setVisibility("自定义薪资".equals(salaryTypeName) ? View.VISIBLE : View.GONE);
            selectPosition = salaryPosition;
        }

        if (!TextUtils.isEmpty(workNo)) {
            List<String> list = new ArrayList<>();
            list.add(workNo);
            entity.setWorkType(list);
            binding.etWorkType.setText(workName);
        }

        if (!TextUtils.isEmpty(workerPerson)) {
            binding.etEmploymentNum.setContent(workerPerson);
        }

        if (mCompanyType == 0){
            binding.etWorkerService.setVisibility(View.GONE);
        }else {
            binding.etWorkerService.setVisibility(View.VISIBLE);
        }

        if (mCompanyType == 2){
            binding.etWorkerService.setVisibility(View.GONE);
        }
    }

    @SuppressLint("WrongConstant")
    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_self_team_employment_edit);
        binding.setViewModel(null);

        fileList = new ArrayList<>();
        binding.etWorkAddress.setOnWholeItemClickListener(this);
        binding.etCategoryName.setOnWholeItemClickListener(this);
        binding.etWorkType.setOnClickListener(this);
        binding.etWorkerStatus.setOnWholeItemClickListener(this);
        binding.etEmploymentUnit.setOnWholeItemClickListener(this);
        binding.etSalaryUnit.setOnWholeItemClickListener(this);
        binding.btnRelease.setOnClickListener(this);
        binding.etWorkerService.setOnWholeItemClickListener(this);
        binding.etSalary.setOnWholeItemClickListener(this);
        binding.iitOtherAsk.setOnWholeItemClickListener(this);

        binding.etEmploymentNum.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.etContactPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        binding.etWorkDuration.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.etSalary.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.etWorkDuration.setCheck(3, 1, false);
        binding.etEmploymentNum.setCheck(3, 1, true);
        binding.etCompanyname.setFilter();
        binding.etProjectName.setFilter();
        binding.etContactName.setFilter();
        binding.etEmploymentNum.setFilter();
        binding.etWorkDuration.setFilter();


        //防止软键盘遮挡输入框
        binding.nestedScrollView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding.nestedScrollView.setFocusable(true);
        binding.nestedScrollView.setFocusableInTouchMode(true);
        binding.nestedScrollView.setOnTouchListener((v, event) -> {
            v.requestFocusFromTouch();
            return false;
        });
        salaryPopWindow = new SalaryRegionPopWindow.Builder(SelfTeamEmploymentEditActivity.this).setBgView(binding.grayLayout)
                .setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                .setCheckText("小时", "天", "月").build();
        salaryPopWindow.setOnResultClick((price, unit, no) -> {
            if (!TextUtils.isEmpty((String) price)) {
                String salary = (String) price;
                if (((String) price).startsWith("-") || ((String) price).endsWith("-")) {
                    salary = ((String) price).replace("-", "");
                }
                binding.etSalary.setContent(salary + "元/" + unit);
                entity.setSalary((String) price);
                entity.setSalaryUnitName((String) unit);
                entity.setSalaryUnit(Integer.valueOf((String) no));
            }
        });
        initPic();
    }

    @Override
    protected void init() {
        entity = new SelfEmploymentEditEntity();
        int companyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (companyType == 2){
            entity.setTeamNo(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""));
        }
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        int id = v.getId();
        if (id == R.id.tv_add_text) {
            if (mNewTextAdapter.getDatas().size() < 3) {
                addNewText();
            } else {
                MToast.showToast(this, "最多只能新增三个字段");
            }
        } else if (id == R.id.et_work_type) {
            if (TextUtils.isEmpty(categoryNo)) {
                MToast.showToast(SelfTeamEmploymentEditActivity.this, "请先选择专业要求");
                return;
            }
            if (isChange) {
                viewModel.getWorkType();
                isFirst = false;
                isChange = false;
            } else {
                if (pickWorkType != null && pickWorkType.size() != 0) {
                    typeSelectWindow.showPopwindow(binding.etWorkerStatus, Gravity.BOTTOM, 0, 0);
                } else {
                    MToast.showToast(SelfTeamEmploymentEditActivity.this, "此专业下无工种");
                }
            }
        } else if (id == R.id.btn_release) {
            disabledView(v);
            if (TextUtils.isEmpty(binding.etCompanyname.getContent())) {
                MToast.showToast(this, binding.etCompanyname.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etProjectName.getContent())) {
                MToast.showToast(this, binding.etProjectName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etContactName.getContent())) {
                MToast.showToast(this, binding.etContactName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etContactPhone.getContent())) {
                MToast.showToast(this, binding.etContactPhone.getContent_edt().getHint().toString());
                return;
            }
            if (!CheckUtils.isMobile(binding.etContactPhone.getContent().trim())) {
                MToast.showToast(this, "请输入正确的联系电话");
                return;
            }
            if (TextUtils.isEmpty(binding.etSalaryUnit.getContent())) {
                MToast.showToast(this, binding.etSalaryUnit.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etSalary.getContent()) && "自定义薪资".equals(binding.etSalaryUnit.getContent())) {
                MToast.showToast(this, binding.etSalary.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etCategoryName.getContent())) {
                MToast.showToast(this, binding.etCategoryName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkType.getText().toString())) {
                MToast.showToast(this, binding.etWorkType.getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etEmploymentNum.getContent())) {
                MToast.showToast(this, binding.etEmploymentNum.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkDuration.getContent())) {
                MToast.showToast(this, binding.etWorkDuration.getContent_edt().getHint().toString());
                return;
            }
            if ("0".equals(binding.etWorkDuration.getContent()) || "0.0".equals(binding.etWorkDuration.getContent()) || "0.".equals(binding.etWorkDuration.getContent())) {
                MToast.showToast(this, "请输入正确的用工时长");
                return;
            }
            if (TextUtils.isEmpty(binding.etEmploymentUnit.getContent())) {
                MToast.showToast(this, binding.etEmploymentUnit.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkAddress.getContent())) {
                MToast.showToast(this, binding.etWorkAddress.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkerStatus.getContent())) {
                MToast.showToast(this, binding.etWorkerStatus.getContent_edt().getHint().toString());
                return;
            }
            if (!"自定义薪资".equals(binding.etSalaryUnit.getContent())) {
                entity.setSalary("0");
                entity.setSalaryUnit(0);
                entity.setSalaryUnitName("");
            }
            entity.setEmploymentCompany(binding.etCompanyname.getContent());
            entity.setProjectName(binding.etProjectName.getContent());
            entity.setEmploymentNumber(Integer.parseInt(binding.etEmploymentNum.getContent()));
            entity.setDuration(Double.valueOf(binding.etWorkDuration.getContent()));
            entity.setContact(binding.etContactName.getContent());
            String temp = binding.etContactPhone.getContent();
            if (binding.etContactPhone.getContent().startsWith("+86")) {
                temp = binding.etContactPhone.getContent().substring(3);
            }
            entity.setContactPhone(temp);
            entity.setEmploymentDescription(binding.etEmploymentDescription.getEditContent());
            mUploadImgList.clear();
            mCurPicNum = -1;
            uploadPic();
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.et_work_address) {
            AMapDialog.launch(this);
        } else if (id == R.id.et_category_name) {
            viewModel.showIndustryPop();
        } else if (id == R.id.et_worker_status) {
            if (null == pickWorkerStatus) {
                viewModel.getEmploymentStatus();
            } else {
                showPickWorkerStatusPop(pickWorkerStatus);
            }
        } else if (id == R.id.et_employment_unit) {
            if (null == pickEmploymentUnit) {
                viewModel.getEmploymentUnit();
            } else {
                showPickEmploymentUnitPop(pickEmploymentUnit);
            }
        } else if (id == R.id.et_salary_unit) {
            showSalaryFsPop(viewModel.getSalaryFs());
        } else if (id == R.id.et_worker_service) {
            viewModel.showCustomerPop();
        } else if (id == R.id.et_address_detail) {
            if (TextUtils.isEmpty(entity.getProvinceNo())) {
                MToast.showToast(this, "请先选择所在地区");
            } else {
                viewModel.getLocationLL(entity.getProvinceNo(), entity.getCityNo(), entity.getAreaNo());
            }
        } else if (id == R.id.et_salary) {
            if (!TextUtils.isEmpty(binding.etSalary.getContent())) {
                if (entity.getSalary().contains("-")) {
                    String[] split = entity.getSalary().split("-");
                    String oneSalary;
                    String twoSalary;
                    if (split.length == 1) {
                        oneSalary = split[0];
                        twoSalary = "";
                    } else {
                        oneSalary = split[0];
                        twoSalary = split[1];
                    }
                    salaryPopWindow.setPopData(oneSalary, twoSalary, entity.getSalaryUnitName());
                } else {
                    salaryPopWindow.setPopData(entity.getSalary(), "", entity.getSalaryUnitName());
                }
            }
            salaryPopWindow.showDownPopwindow(binding.grayLayout, true);
        } else if (id == R.id.iit_other_ask) {
            ActivityJump.jumpToActivityForResult(this, OtherAskActivity.class, 0, Pair.create("result", addField));
        }
    }

    private void release() {
        if (mUploadImgList.size() != 0) {
            List<SelfEmploymentEditEntity.FileDTOListBean> fileDTOListBeanList = new ArrayList<>();
            for (String s : mUploadImgList) {
                SelfEmploymentEditEntity.FileDTOListBean fileDTOListBean = new SelfEmploymentEditEntity.FileDTOListBean();
                List<String> list = new ArrayList<>();
                list.add(s);
                fileDTOListBean.setUrl(list);
                fileDTOListBeanList.add(fileDTOListBean);
            }
            entity.setFileDTOList(fileDTOListBeanList);
        } else {
            entity.setFileDTOList(null);
        }
        viewModel.uploadEmployment(entity);
    }

    private void initPic() {
        mCacheImgMap = new HashMap<>();
        mUploadImgList = new ArrayList<>();
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        binding.rvPic.setLayoutManager(manager);
        mPicAdapter = new ImageAdapter(this, new ArrayList<>(), new ArrayList<>(), 9);
        binding.rvPic.setHasFixedSize(false);
        binding.rvPic.addItemDecoration(new GridSpacingItemDecoration(3, ScreenUtils.dip2px(this, 2), false));
        binding.rvPic.setAdapter(mPicAdapter);
        //初始化数据
        if (mNewTextAdapter == null) {
            mNewTextAdapter = new NewTextAdapter(getActivity(), null);
        }
        mNewTextAdapter.setOnClose(position -> mNewTextAdapter.removeItem(position));
    }

    private void addNewText() {
        SelfEmploymentEditEntity.NewText emtData;
        List<SelfEmploymentEditEntity.NewText> EMTList;
        emtData = new SelfEmploymentEditEntity.NewText();
        emtData.setContent("");
        emtData.setName("");
        EMTList = new ArrayList<>();
        EMTList.add(emtData);
        mNewTextAdapter.addDatas(EMTList);
        mNewTextAdapter.upDate();
    }

    private void uploadPic() {
        mCurPicNum++;
        int size = mPicAdapter.getFileList().size();
        if (mUploadImgList.size() <= 0) {
            mUploadImgList.addAll(mPicAdapter.getNetUrls());
        }

        if (size > 0 && mCurPicNum < size) {
            String path = mPicAdapter.getUrls().get(mCurPicNum);
            // 过滤已上传的
            if (!TextUtils.isEmpty(mCacheImgMap.get(path))) {
                uploadPic();
            } else {
                File file = mPicAdapter.getFileList().get(mCurPicNum);
                viewModel.uploadMultiFileModel(file, mCurPicNum + 1, size);
            }
        } else {
            release();
        }
    }

    /**
     * 图片上传回调
     *
     * @param fromString
     * @param toString
     */
    public void uploadPicInfo(String fromString, String toString) {
        mUploadImgList.add(toString);
        mCacheImgMap.put(fromString, toString);
        uploadPic();
    }

    /**
     * 所在地区选择
     *
     * @param data
     */
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(SelfTeamEmploymentEditActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                entity.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                entity.setAreaName(areaName);
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.etWorkAddress.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            entity.setProvinceName(addressEntityList.get(options1).getName());
            entity.setProvinceNo(addressEntityList.get(options1).getId());
            entity.setCityName(opt2.get(options1).get(options2).getName());
            entity.setCityNo(opt2.get(options1).get(options2).getNo());
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                default:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (entity != null && entity.getProvinceName() != null && entity.getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (entity != null) {
            if (entity.getCityName() != null) {
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (entity.getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            }
            if (entity.getAreaName() != null) {
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (entity.getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public void showEmploymentSalaryUnitPop(List<PickSelectEntity> list) {
        if (null == pickEmploymentSalaryUnit) {
            pickEmploymentSalaryUnit = new ArrayList<>();
            pickEmploymentSalaryUnit.addAll(list);
        }
        if (pickEmploymentSalaryUnit.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamEmploymentEditActivity.this, (options1, options2, options3, v) -> {
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickEmploymentSalaryUnit);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    /**
     * 薪资方式
     *
     * @param list 薪资方式的数据
     */
    public void showSalaryFsPop(List<PickSelectEntity> list) {
        OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamEmploymentEditActivity.this, (options1, options2, options3, v) -> {
            binding.etSalaryUnit.setContent(list.get(options1).getProjectscale());
            entity.setSalaryType(Integer.valueOf(list.get(options1).getNo()));
            binding.etSalary.setVisibility("自定义薪资".equals(list.get(options1).getProjectscale()) ? View.VISIBLE : View.GONE);
            selectPosition = options1;
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        projectCategoryOption.setPicker(viewModel.getSalaryFs());
        projectCategoryOption.setSelectOptions(selectPosition);
        projectCategoryOption.setTitleText("选择薪资方式");
        projectCategoryOption.show();
    }

    public void showPickWorkTypePop(List<AddressEntity> list) {
        Collections.reverse(list);
        if (list == null || list.size() == 0) {
            MToast.showToast(SelfTeamEmploymentEditActivity.this, "此专业下无工种");
            pickWorkType = null;
            return;
        }
        if (null == pickWorkType) {
            pickWorkType = new ArrayList<>();
            pickWorkType.addAll(list);
        }
        if (pickWorkType.size() > 0) {
            typeSelectWindow = new PackerSignUpWindow(SelfTeamEmploymentEditActivity.this);
            typeSelectWindow.setSelectResultClick((pickSelectEntities, name) -> {
                workTypeListNO = new ArrayList<>();
                for (PickSelectEntity pickSelectEntity : pickSelectEntities) {
                    workTypeListNO.add(pickSelectEntity.getNo());
                }
                entity.setWorkType(workTypeListNO);
                binding.etWorkType.setText(name);
            });
            typeSelectWindow.setMostSelected(20);
            typeSelectWindow.setBgView(binding.grayLayout);
            List<PickSelectEntity> pickSelectEntities = new ArrayList<>();
            for (AddressEntity addressEntity : list) {
                pickSelectEntities.add(new PickSelectEntity(addressEntity.getNo(),addressEntity.getName()));
            }
            typeSelectWindow.setWorkTypeData(pickSelectEntities);
            if (!TextUtils.isEmpty(workNo)) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getNo().equals(workNo)){
                        workCityPosition3 = i;
                    }
                }
                typeSelectWindow.setDefaultItem(workCityPosition3);
            }
            if (!isFirst) {
                typeSelectWindow.showPopwindow(binding.etWorkType, Gravity.BOTTOM, 0, 0);
            }

        }
    }

    public void showPickWorkerTypePop(List<PickSelectEntity> list) {
        if (null == pickWorkerType) {
            pickWorkerType = new ArrayList<>();
            pickWorkerType.addAll(list);
        }
        if (pickWorkerType.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamEmploymentEditActivity.this, (options1, options2, options3, v) -> {
                entity.setEmploymentType(Integer.parseInt(pickWorkerType.get(options1).getNo()));
                entity.setEmploymentTypeName(pickWorkerType.get(options1).getProjectscale());
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickWorkerType);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    public void showPickWorkerStatusPop(List<PickSelectEntity> list) {
        if (null == pickWorkerStatus) {
            pickWorkerStatus = new ArrayList<>();
            pickWorkerStatus.addAll(list);
        }
        if (pickWorkerStatus.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamEmploymentEditActivity.this, (options1, options2, options3, v) -> {
                binding.etWorkerStatus.setContent(pickWorkerStatus.get(options1).getProjectscale());
                entity.setEmploymentStatus(Integer.parseInt(pickWorkerStatus.get(options1).getNo()));
                entity.setEmploymentStatusName(pickWorkerStatus.get(options1).getProjectscale());
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickWorkerStatus);
            projectCategoryOption.setTitleText("请选择用工状态");
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    public void showPickEmploymentUnitPop(List<PickSelectEntity> list) {
        if (null == pickEmploymentUnit) {
            pickEmploymentUnit = new ArrayList<>();
            pickEmploymentUnit.addAll(list);
        }
        if (pickEmploymentUnit.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamEmploymentEditActivity.this, (options1, options2, options3, v) -> {
                binding.etEmploymentUnit.setContent(pickEmploymentUnit.get(options1).getProjectscale());
                entity.setDurationUnit(Integer.parseInt(pickEmploymentUnit.get(options1).getNo()));
                entity.setDurationUnitName(pickEmploymentUnit.get(options1).getProjectscale());
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickEmploymentUnit);
            projectCategoryOption.setTitleText("选择用工时长单位");
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                mUploadImgList.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    mUploadImgList.add(localMedia.getRealPath());
                }
                mPicAdapter.setDatas(selectList, mUploadImgList);
                mPicAdapter.setFileList(fileList);
            }
            if (requestCode == 255) {
                if (data == null) {
                    return;
                }
                setAddressText(data);
            }
        }

        if (resultCode == 1) {
            if (requestCode == 0) {
                addField = (OtherAskTransmitEntity) data.getSerializableExtra("result");
                if (addField != null) {
                    binding.iitOtherAsk.setDeliverLineVG(true);
                    entity.setStayCondition(addField.getConditionsOfResidence());
                    entity.setDietCondition(addField.getEatingConditions());
                    entity.setSalaryManager(addField.getSalaryManagementNo());
                    entity.setPayRoll(addField.getPayrollPaymentNo());
                    entity.setProfessClothing(addField.getProfessionalClothing());
                    entity.setAgeRquirement(addField.getAgeRequirementsNo());
                    entity.setSexRquirement(addField.getSexRequirementsNo());
                    entity.setNationRquirement(addField.getEthnicRequirementsNo());
                    entity.setWorkYearRquirement(addField.getLengthOfServiceNo());
                    entity.setHealthProve(addField.getMedicalCertificateNo());
                    entity.setPerformanceRquirement(addField.getPerformanceRequirements());
                    entity.setNationRquirementName(addField.getEthnicRequirementsName());
                    List<SelfEmploymentEditEntity.NewText> list = new ArrayList<>();
                    for (int i = 0; i < addField.getAddField().size(); i++) {
                        list.add(new SelfEmploymentEditEntity.NewText(addField.getAddField().get(i).getContent(), addField.getAddField().get(i).getName()));
                    }
                    entity.setNewFiledArr(list);
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.rl_team_employment_other_ask, OtherAskFragment.newInstance(addField));
                    transaction.commit();
                }
            }
        }

        if (requestCode == RequestCode.CODE_MAP) {
            AMapAddressEntity entity = AMapDialog.get(data);
            getAddress(entity);
        }
    }

    private void getAddress(AMapAddressEntity entity) {
        if (entity != null) {
            this.entity.setProvinceNo(entity.getProvinceNo());
            if (entity.getProvince().equals("北京") && entity.getProvince().equals("天津") && entity.getProvince().equals("上海") && entity.getProvince().equals("重庆")) {
                this.entity.setProvinceName(entity.getProvince() + "市");
                entity.setProvince(entity.getProvince() + "市");
            } else if (entity.getProvince().equals("内蒙古") && entity.getProvince().equals("西藏")) {
                this.entity.setProvinceName(entity.getProvince() + "自治区");
                entity.setProvince(entity.getProvince() + "自治区");
            } else if (entity.getProvince().equals("广西")) {
                this.entity.setProvinceName(entity.getProvince() + "壮族自治区");
                entity.setProvince(entity.getProvince() + "壮族自治区");
            } else if (entity.getProvince().equals("宁夏")) {
                this.entity.setProvinceName(entity.getProvince() + "回族自治区");
                entity.setProvince(entity.getProvince() + "回族自治区");
            } else if (entity.getProvince().equals("新疆")) {
                this.entity.setProvinceName(entity.getProvince() + "维吾尔族自治区");
                entity.setProvince(entity.getProvince() + "维吾尔族自治区");
            } else if (entity.getProvince().equals("香港") && entity.getProvince().equals("澳门")) {
                this.entity.setProvinceName(entity.getProvince() + "特别行政区");
                entity.setProvince(entity.getProvince() + "特别行政区");
            } else {
                this.entity.setProvinceName(entity.getProvince() + "省");
                entity.setProvince(entity.getProvince() + "省");
            }
            this.entity.setCityNo(entity.getCityNo());
            this.entity.setCityName(entity.getCity() + "市");
            this.entity.setAreaNo(entity.getDistrictNo());
            this.entity.setAreaName(entity.getDistrict() + "区");
            this.entity.setLongitude(String.valueOf(entity.getLongitude()));
            this.entity.setLatitude(String.valueOf(entity.getLatitude()));
            this.entity.setAddress(String.format("%s%s%s%s", entity.getProvince(), entity.getCity(), entity.getDistrict(), entity.getSnippet()));
            binding.etWorkAddress.setContent(String.format("%s%s%s%s", entity.getProvince(), entity.getCity(), entity.getDistrict(), entity.getSnippet()), 13);
        }
    }

    public void setAddressText(Intent data) {
        double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
        double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
        String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
        entity.setLongitude(lon + "");
        entity.setLatitude(lat + "");
        entity.setAddress(address);
    }

    public void updateTeamEmploymentEntity(SelfEmploymentEditEntity data) {
        if (data != null) {
            entity = data;

            addField = new OtherAskTransmitEntity();
            addField.setConditionsOfResidence(data.getStayCondition());
            addField.setEatingConditions(data.getDietCondition());
            addField.setSalaryManagementNo(data.getSalaryManager());
            switch (data.getSalaryManager()) {
                case "1":
                    addField.setSalaryManagementName("保底工资");
                    break;
                case "2":
                    addField.setSalaryManagementName("绩效方式");
                    break;
                default:
                    break;
            }
            addField.setPayrollPaymentNo(data.getPayRoll());
            switch (data.getPayRoll()) {
                case "1":
                    addField.setPayrollPaymentName("月");
                    break;
                case "2":
                    addField.setPayrollPaymentName("季度");
                    break;
                case "3":
                    addField.setPayrollPaymentName("年");
                    break;
                default:
                    break;
            }
            addField.setProfessionalClothing(data.getProfessClothing());
            addField.setAgeRequirementsNo(data.getAgeRquirement());
            switch (data.getAgeRquirement()) {
                case "1":
                    addField.setAgeRequirementsName("不限");
                    break;
                case "2":
                    addField.setAgeRequirementsName("15-25岁");
                    break;
                case "3":
                    addField.setAgeRequirementsName("25-35岁");
                    break;
                case "4":
                    addField.setAgeRequirementsName("35-45岁");
                    break;
                case "5":
                    addField.setAgeRequirementsName("45-55岁");
                    break;
                case "6":
                    addField.setPayrollPaymentName("55岁以上");
                    break;
                default:
                    addField.setPayrollPaymentName("");
                    break;
            }
            addField.setSexRequirementsNo(data.getSexRquirement());
            switch (data.getSexRquirement()) {
                case "1":
                    addField.setSexRequirementsName("不限");
                    break;
                case "2":
                    addField.setSexRequirementsName("男");
                    break;
                case "3":
                    addField.setSexRequirementsName("女");
                    break;
                default:
                    break;
            }
            addField.setEthnicRequirementsNo(data.getNationRquirement());
            addField.setEthnicRequirementsName(data.getNationRquirementName());
            addField.setLengthOfServiceNo(data.getWorkYearRquirement());
            switch (data.getWorkYearRquirement()) {
                case "1":
                    addField.setLengthOfServiceName("不限");
                    break;
                case "2":
                    addField.setLengthOfServiceName("1年内");
                    break;
                case "3":
                    addField.setLengthOfServiceName("1-3年");
                    break;
                case "4":
                    addField.setLengthOfServiceName("3-5年");
                    break;
                case "5":
                    addField.setLengthOfServiceName("5-10年");
                    break;
                case "6":
                    addField.setLengthOfServiceName("10年以上");
                    break;
                default:
                    addField.setLengthOfServiceName("");
                    break;
            }
            addField.setMedicalCertificateNo(data.getHealthProve());
            switch (data.getHealthProve()) {
                case "1":
                    addField.setMedicalCertificateName("需要");
                    break;
                case "2":
                    addField.setMedicalCertificateName("不需要");
                    break;
                default:
                    break;
            }
            addField.setPerformanceRequirements(data.getPerformanceRquirement());
            if (data.getNewFiledArr() != null) {
                List<OtherAskTransmitEntity.AddFiled> list = new ArrayList<>();
                for (int i = 0; i < data.getNewFiledArr().size(); i++) {
                    list.add(new OtherAskTransmitEntity.AddFiled(data.getNewFiledArr().get(i).getName(), data.getNewFiledArr().get(i).getContent()));
                }
                addField.setAddField(list);
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.rl_team_employment_other_ask, OtherAskFragment.newInstance(addField));
            transaction.commit();

            binding.setViewModel(entity);
            categoryNo = data.getCategoryNo();
            mUploadImgList.clear();
            for (SelfEmploymentEditEntity.FileDTOListBean bean : data.getFileDTOList()) {
                if (!TextUtils.isEmpty(bean.getUrl().get(0))) {
                    mUploadImgList.add(bean.getUrl().get(0));
                }
            }
            if (data.getNewFiledArr() != null && data.getNewFiledArr().size() != 0) {
                mNewTextAdapter.addDatas(data.getNewFiledArr());
            }
            binding.etSalary.setVisibility("自定义薪资".equals(data.getSalaryTypeName()) ? View.VISIBLE : View.GONE);
            binding.etWorkType.setText(entity.getWorkTypeName());
            mPicAdapter.setNetImgList(mUploadImgList);
            binding.etEmploymentNum.setContent(entity.getEmploymentNumber() + "");
            binding.etWorkDuration.setContent(PointUtils.originalPrice(entity.getDuration()) + "");
            String salary;
            String salaryOld = data.getSalary();
            if (data.getSalary().startsWith("-") || data.getSalary().endsWith("-")) {
                salary = salaryOld.replace("-", "");
            } else {
                salary = data.getSalary();
            }

            binding.etSalary.setContent(!"自定义薪资".equals(data.getSalaryTypeName()) ? "" : salary + "元/" + entity.getSalaryUnitName());
            binding.etWorkAddress.setContent(String.format("%s%s%s%s", entity.getProvinceName(), entity.getCityName(), entity.getAreaName(), entity.getAddress()), 13);
            isFirst = true;
            viewModel.getWorkType();
        }
    }

    public void uploadEmploymentResult() {
        setResult(RESULT_OK);
        NumberConstant.sIsBack = 1;
        finish();
    }

    public void updateCustomer(PickSelectEntity serviceEntity) {
        entity.setImName(serviceEntity.getProjectscale());
        entity.setImId(serviceEntity.getNo());
        binding.etWorkerService.setContent(serviceEntity.getProjectscale());
    }

    public void updateAddress(MapLongAndLatEntity data) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }

    public void selectedIndustry(PickSelectEntity<List<PickSelectEntity>> opt1, PickSelectEntity opt2) {
        binding.etCategoryName.setContent(String.format("%s-%s",opt1.getProjectscale(),opt2.getProjectscale()),17);
        if (!opt1.getNo().equals(entity.getIndustryNo()) || !opt2.getNo().equals(entity.getCategoryNo())) {
            isChange = true;
        }
        industryNo = opt1.getNo();
        entity.setIndustryNo(opt1.getNo());
        entity.setIndustryName(opt1.getProjectscale());
        entity.setCategoryNo(opt2.getNo());
        entity.setCategoryName(opt2.getProjectscale());
        categoryNo = opt2.getNo();
        binding.etWorkType.setText("");
    }

    public void uploadFail() {

    }

    public void disabledView(final View v) {
        v.setClickable(false);
        // 延迟5秒，恢复点击事件
        new Handler().postDelayed(() -> v.setClickable(true), 5000);
    }

}